const fp = require('fastify-plugin');
const _nunjucks = require('nunjucks');


async function createInstance(fastify, options) {

  fastify.decorateReply('assgin',function (key, value) {
    this.renderData = Object.assign(this.renderData, {[key]: value});
  })

  fastify.decorateReply('display', function (html) {
    // console.log(this.request.raw.url)
    const paths = this.request.raw.url.split('/');
    let htmlName = '';
    if (saas.isEmpty(htmlName)) {
      htmlName = paths[paths.length - 1]+'.html';
    }

    let view = '';
    for (let i = 0; i < paths.length; i++) {
      if (i < paths.length) {
        view += '/' + paths[i];
      }
    }
    _nunjucks.configure(view, {autoescape: true});
    const data = _nunjucks.render(htmlName, this.renderData);
    this.type('text/html'); // this 是 'Reply' 对象
    this.send(data);
  })

}

module.exports = fp(createInstance);
